package com.cjg.netCode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class threadChatUdp implements Runnable{
    DatagramSocket ds = null;
    BufferedReader bufferedReader =null;
    private String  toIp;
    private int toPort;
    private int fromPort;

    public threadChatUdp(String toIp, int toPort, int fromPort) {
        this.toIp = toIp;
        this.toPort = toPort;
        this.fromPort = fromPort;
        try {
            ds= new DatagramSocket(fromPort);
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {



        while (true){
            String s = null;
            try {
                s = bufferedReader.readLine();
                byte[] bytes = s.getBytes();
                int length = bytes.length;

                InetSocketAddress socket = new InetSocketAddress(toIp, toPort);
                DatagramPacket datagramPacket = new DatagramPacket(bytes,0,length,socket);
                ds.send(datagramPacket);
                if (s.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        ds.close();
    }
}
